<?php
$server = new \Swoole\WebSocket\Server("0.0.0.0", 9999);

//多端口监听
//下面的是Http 请求 端口是10000
$http = $server->listen("0.0.0.0", 10000,SWOOLE_SOCK_TCP);
$http->on("request", function ($request, $response) {
    $data = $request->post;
    $redis = new \Swoole\Coroutine\Redis();
    $redis->connect('127.0.0.1', '6379');
    $msg = $err = "";
    foreach ($data as $k => $v) {
        $queue = $redis->lRange("zgjz",0,-1);
        if($queue && in_array($v,$queue)){
            $err = $err."座位{$v},";
        }else{
            $redis->lPush("zgjz",$v);
            $msg = $msg."座位{$v}";
        }
    };
    if($err){
        $err = $err."购买失败";
    }
    if($msg){
        $msg = $msg."购买成功";
    }
    return $response->end(json_encode(['status'=>'0',"msg"=>$msg,"err"=>$err]));
});

$server->on("connect", function (\Swoole\WebSocket\Server $server, $fd) {
   echo "Client {$fd} connected\n";
});
$server->on("open", function (\Swoole\WebSocket\Server $server, $req) {
    echo "222====服务端与客户端建立连接成功===".PHP_EOL;
    $server->push($req->fd,json_encode(["event"=>"ping","data"=>"connect server successed"]));
});

$server->on("message", function ($server, $frame) {
    echo "Client {$frame->fd} received message: {$frame->data}\n";
    $redis = new \Swoole\Coroutine\Redis();
    $redis->connect('127.0.0.1', '6379');
    $queue  = $redis->lRange("zgjz",0,-1);
    var_dump(count($server->connections));
    foreach ($server->connections as $fd) {
        if($server->isEstablished($fd)) {
            $server->push($fd,json_encode(["event"=>"move","data"=>$queue]));
        }
    }
});

$server->on("close", function ($server, $fd) {
    echo "Client {$fd} closed\n";
});

$server->start();